package com.ruoyi.web.controller.publish;

import java.io.*;
import java.util.*;
import java.util.regex.Pattern;

import com.ruoyi.common.config.ServerConfig;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.framework.web.domain.server.Sys;
import com.ruoyi.publish.domain.IdAcceptRegister;
import com.ruoyi.publish.domain.IdReport;
import com.ruoyi.publish.mapper.IdIdentsampleMapper;
import com.ruoyi.publish.mapper.IdReportMapper;
import com.ruoyi.publish.service.IIdAcceptRegisterService;
import com.ruoyi.system.utils.QrCodeUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.publish.domain.IdIdentsample;
import com.ruoyi.publish.service.IIdIdentsampleService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 鉴定样本Controller
 *
 * @author 张泽望
 * @date 2020-11-05
 */
@Controller
@RequestMapping("/publish/identsample")
public class IdIdentsampleController extends BaseController {
    private String prefix = "publish/identsample";

    @Autowired
    private IIdIdentsampleService idIdentsampleService;

    @Autowired
    private IIdAcceptRegisterService idAcceptRegisterService;

    @Autowired
    private IdIdentsampleMapper idIdentsampleMapper;

    @Autowired
    private ServerConfig serverConfig;


    //    @RequiresPermissions("publish:identsample:view")
    @GetMapping()
    public String identsample() {
        return prefix + "/identsample";
    }

    /**
     * 查询鉴定样本列表
     */
//    @RequiresPermissions("publish:identsample:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(IdIdentsample idIdentsample) {
        startPage();
        List<IdIdentsample> list = idIdentsampleService.selectIdIdentsampleList(idIdentsample);
        return getDataTable(list);
    }

    /**
     * 查询鉴定样本列表
     */
//    @RequiresPermissions("publish:identsample:listByIds")
    @GetMapping("/listByIds/{ids}")
    @ResponseBody
    public TableDataInfo listByIds(@PathVariable("ids") String ids) {
        List<IdIdentsample> list = new ArrayList<>();
        String[] strArr = ids.split(",");
        for (String id : strArr) {
            Long idd = Long.valueOf(id);
            IdIdentsample idIdentsample = idIdentsampleService.selectIdIdentsampleById(idd);
            list.add(idIdentsample);
        }
        return getDataTable(list);
    }

    /**
     * 查询鉴定样本列表
     */
//    @RequiresPermissions("publish:identsample:list")
    @PostMapping("/listSampRegs")
    @ResponseBody
    public TableDataInfo listSampRegis(IdIdentsample idIdentsample) {
        startPage();
        List<IdIdentsample> list = idIdentsampleService.selectIdIdentsampleRegisterList(idIdentsample);
        //查询样本是否都为已鉴定状态,用户手动刷新样本页面。
        if (StringUtils.isNotEmpty(list)) {
            boolean isStatus = true;
            for (IdIdentsample identsample : list) {
                String status = identsample.getStatus();
                if ("1".equals(status) || "0".equals(status) || StringUtils.isEmpty(status)) {
                    isStatus = false;
                    break;
                }
            }
            if (isStatus && idIdentsample.getRegisterId() != null) {
                IdAcceptRegister idAcceptRegister = idAcceptRegisterService.selectIdAcceptRegisterById(idIdentsample.getRegisterId());
                idAcceptRegister.setAuditStatus("6");
                idAcceptRegisterService.updateIdAcceptRegister(idAcceptRegister);
            }
        }
        return getDataTable(list);
    }
    //    从鉴定记录查看样本
//    @RequiresPermissions("publish:identsample:view")
    @GetMapping("/listByRegister")
    public String identsampleyRegister(Long registerId, ModelMap mmap) {

        if (registerId != null) {
            IdAcceptRegister idAcceptRegister = idAcceptRegisterService.selectIdAcceptRegisterById(registerId);
            System.out.println(idAcceptRegister);
            if (idAcceptRegister != null) {
                mmap.put("registerId", registerId);
            }else{
                mmap.put("registerId", 0);

            }

            return prefix + "/identsampleByRegister";

        }
        return "error";
    }

    //    从文书管理查看已参与生成协查函样本
//    @RequiresPermissions("publish:identsample:view")
    @GetMapping("/identsampleByAssist")
    public String identsampleByAssist(Long registerId, ModelMap mmap) {

        if (registerId != null) {
            IdAcceptRegister idAcceptRegister = idAcceptRegisterService.selectIdAcceptRegisterById(registerId);
            System.out.println(idAcceptRegister);
            if (idAcceptRegister != null) {
                mmap.put("registerId", registerId);
            }else{
                mmap.put("registerId", 0);

            }

            return prefix + "/identsampleByAssist";

        }
        return "error";
    }

    //    从文书管理查看已参与生成协查函样本列表
    @PostMapping("/identsampleListByAssist")
    @ResponseBody
    public TableDataInfo identsampleListByAssist(IdIdentsample idIdentsample) {
        startPage();
        idIdentsample.setBy3("1");//by3标记为已参与生成协查函
        List<IdIdentsample> list = idIdentsampleService.selectIdIdentsampleRegisterList(idIdentsample);
        return getDataTable(list);
    }


    /**
     * 导出鉴定样本列表
     */
//    @RequiresPermissions("publish:identsample:export")
    @Log(title = "鉴定样本", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(IdIdentsample idIdentsample) {
        List<IdIdentsample> list = null;
        if (StringUtils.isNotEmpty(idIdentsample.getExportIds())) {
            list = idIdentsampleService.selectRecordByIds(idIdentsample.getExportIds().split(","));
        } else {
            list = idIdentsampleService.selectIdIdentsampleRegisterList(idIdentsample);
        }
        ExcelUtil<IdIdentsample> util = new ExcelUtil<IdIdentsample>(IdIdentsample.class);
        return util.exportExcel(list, "identsample");
    }


    @Log(title = "鉴定样本excel导入", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport, Long registerId) throws Exception {
        if (registerId == null) {
            return error("案件记录不能为空");
        }
        byte[] bytes = file.getBytes();
        InputStream in = new ByteArrayInputStream(bytes);

        ExcelUtil<IdIdentsample> util = new ExcelUtil<IdIdentsample>(IdIdentsample.class);
        List<IdIdentsample> idIdentsampleList = util.importExcel(in);

        System.out.println("sieze=" + idIdentsampleList.size());
        String operName = ShiroUtils.getSysUser().getLoginName();
        String userName = ShiroUtils.getSysUser().getUserName();

        System.out.println("operName="+operName+"");
        String message = idIdentsampleService.importIdIdentsample(idIdentsampleList, updateSupport, operName,userName, "2020", registerId);
        return AjaxResult.success(message);
    }


    //    @RequiresPermissions("system:user:view")
    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate() {
        ExcelUtil<IdIdentsample> util = new ExcelUtil<IdIdentsample>(IdIdentsample.class);
        List<IdIdentsample> list = new ArrayList<>();
        IdIdentsample idIdentsample = new IdIdentsample();
        IdAcceptRegister idAcceptRegister = new IdAcceptRegister();
        //样本名称
        idIdentsample.setSampleName("样本名称(示范)");
        //送鉴单位
        idAcceptRegister.setSendUnit("重庆出版社(示范)");
        //来文文号
        idAcceptRegister.setDocumentNum("121501(示范)");
        idIdentsample.setIdAcceptRegister(idAcceptRegister);

        //系来函所附清单的序号：
        idIdentsample.setLetterOrder("20210102(示范)");

        //样本数量：
        idIdentsample.setSampleNumber("2");

        //样本ID
        idIdentsample.setSampleCode("2020-46-3-1");
        //样本录入日期
        idIdentsample.setCreateTime(new Date());
        //样本类别
        idIdentsample.setSampleType("报纸");
        //接办人
        idIdentsample.setTakeoverUser("admin");
        list.add(idIdentsample);
        return util.importDataTemplateExcel(list, "样本数据");
    }


    /**
     * 新增鉴定样本
     */
    @GetMapping("/add/{registerId}")
    public String add(@PathVariable("registerId") Long registerId, ModelMap mmap) {
        if (registerId != null) {
            IdAcceptRegister idAcceptRegister = idAcceptRegisterService.selectIdAcceptRegisterById(registerId);
            if (idAcceptRegister != null) {
                mmap.put("registerId", registerId);
            }

            return prefix + "/add";
        }
//        获得送检单位 来文文号 接办人 鉴定小组组长 状态
//        String sendUnit=idAcceptRegister.getSendUnit();
//        String documentNum=idAcceptRegister.getDocumentNum();
//        Long   groupId=idAcceptRegister.getGroupId();
//        String groupLeader=idAcceptRegister.getGroupLeader();


        return null;
    }

    /**
     * 新增保存鉴定样本
     */
//    @RequiresPermissions("publish:identsample:add")
    @Log(title = "鉴定样本", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(IdIdentsample idIdentsample) {
//        idIdentsample.setSampleCode("code");
        idIdentsample.setTakeoverUser(ShiroUtils.getSysUser().getUserName());
        idIdentsample.setCreateTime(new Date());
        idIdentsample.setCreateBy(ShiroUtils.getLoginName());

        //版权识别信息 过滤
        if (StringUtils.isNotEmpty(idIdentsample.getPublishInfoText())){
            idIdentsample.setPublishInfoText(filtration(idIdentsample.getPublishInfoText()));
        }

        return toAjax(idIdentsampleService.insertIdIdentsample(idIdentsample));
    }

    /**
     * 修改鉴定样本
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap) {
        IdIdentsample idIdentsample = idIdentsampleService.selectIdIdentsampleById(id);
        mmap.put("idIdentsample", idIdentsample);
        return prefix + "/edit";
    }

    /**
     * 修改保存鉴定样本
     */
//    @RequiresPermissions("publish:identsample:edit")
    @Log(title = "鉴定样本", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(IdIdentsample idIdentsample) {
        //版权识别信息 过滤
        if (StringUtils.isNotEmpty(idIdentsample.getPublishInfoText())){
            idIdentsample.setPublishInfoText(filtration(idIdentsample.getPublishInfoText()));
        }
        return toAjax(idIdentsampleService.updateIdIdentsample(idIdentsample));
    }

    @GetMapping("/detail/{id}")
    public String detail(@PathVariable("id") Long id, ModelMap mmap) {
        IdIdentsample idIdentsample = idIdentsampleService.selectIdIdentsampleById(id);
        mmap.put("idIdentsample", idIdentsample);
        return prefix + "/detail";
    }

    /**
     * 删除鉴定样本
     */
//    @RequiresPermissions("publish:identsample:remove")
    @Log(title = "鉴定样本", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(idIdentsampleService.deleteIdIdentsampleByIds(ids));
    }


    /**
     * 是否启用状态修改
     */
    @Log(title = "鉴定受理登记", businessType = BusinessType.UPDATE)
//    @RequiresPermissions("publish:identsample:edit")
    @PostMapping("/changeStatus")
    @ResponseBody
    public AjaxResult changeStatus(IdIdentsample idIdentsample) {
        return toAjax(idIdentsampleService.changeStatus(idIdentsample));
    }

    /**
     * 显示二维码
     */
    @Log(title = "鉴定样本", businessType = BusinessType.DELETE)
    @GetMapping("/qrCode")
    @ResponseBody
    public void remove(IdIdentsample idIdentsample, HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获得记录id再生成 二维码返回前端
        // 判断 鉴定登记是否审核通过
        //
        //

//        IdIdentsample entity = idIdentsampleService.selectIdIdentsampleById(idIdentsample.getId());
//        if(entity.getBy1()==null){
//            response.setContentType("image/png");
//            response.setCharacterEncoding("utf-8");
//            String content = "待鉴定";
//            QrCodeUtils.testGetImage(content, response);
//        }else {
//        IdAcceptRegister register=idAcceptRegisterService.selectIdAcceptRegisterById(entity.getRegisterId());
//            IdReport report = idReportMapper.selectIdReportById(Long.valueOf(entity.getBy1()));
//            if (entity.getId() != null && report.getId() != null) {
        String url = serverConfig.getUrl() + "/publish/report/apprReport/" + idIdentsample.getId() + "?mobile=true";
        response.setContentType("image/png");
        response.setCharacterEncoding("utf-8");
        String content = url;
        QrCodeUtils.testGetImage(content, response);
//            }
//        }

    }


    /**
     * @Description: 鉴定样本多选
     * @Param: []
     * @return: java.lang.String
     * @Author: 张泽望
     * @Date: 2020/11/17
     */
//    @RequiresPermissions("publish:identsample:view")
    @GetMapping("/identsampleCheck")
    public String identsampleCheck(HttpServletRequest request, HttpServletResponse response, ModelMap mmap) {
        String registerId = request.getParameter("registerId");
        String appraCon = request.getParameter("appraCon");
        String reportId = request.getParameter("reportId");//鉴定报告id

        //鉴定报告修改前选择的样本记录
//        IdReport  report=idReportMapper.selectIdReportById(re)
        //现在要显示之前 保存的案例
        mmap.put("reportId", reportId);
        mmap.put("registerId", registerId);
        mmap.put("appraCon", appraCon);
        return prefix + "/identsampleCheck";
    }


    @GetMapping("/indexOne")
    public String indexOne(HttpServletRequest request, HttpServletResponse response, ModelMap mmap) {
        String parameter = request.getParameter("parameter");
        mmap.put("parameter",parameter);
        return prefix + "/indexOne";
    }


    public static String filtration(String str) {
        String regEx = "[`~!@#$%^&*()+=|{}:;\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？']";
        str = Pattern.compile(regEx).matcher(str).replaceAll("").trim();
        System.out.println("str ======" + str + ".");

        return str;
    }

    /**
     * 点击变成完结状态时间的后台判断 进行不同的提示语言
     */
//    @Log(title = "鉴定受理登记", businessType = BusinessType.UPDATE)
//    @RequiresPermissions("publish:identsample:edit")
    @PostMapping("/getSampleInfo")
    @ResponseBody
    public AjaxResult changeStatus(Long id) {
        //判断是否有 鉴定样本未被鉴定
        IdIdentsample sampleQuery=new IdIdentsample();
        sampleQuery.setRegisterId(id);
        Map<String,Object> map=new HashMap<>();
        map.put("isReport","noNull");
        map.put("reportId",null);

        sampleQuery.setParams(map);
        List<IdIdentsample>  noCheck=idIdentsampleService.selectIdIdentsampleRegisterList(sampleQuery);
        AjaxResult  result=success();
        //如果
        if (noCheck.size()!=0){
            result.put("status",0);// 存在未被鉴定的鉴定样本
        }else{
            result.put("status",1);// 不存在未被鉴定的鉴定样本

        }

        return result;

    }

}
